<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElButton, ElInput, ElRadioGroup, ElRadio } from 'element-plus';
import { DocumentCopy } from '@element-plus/icons-vue';
import EasyQRCode from 'easyqrcodejs';

import { useUseStore } from "@/stores/user";
import TopButton from "@/components/Pengyq/TopButton.vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { ElTable, ElTableColumn } from 'element-plus'
import { ToastFun } from "@/hook/toast";
import { computedBuyeCNYApi } from "@/server/web3.js"
import { getUserInfoAPI, selectUserWithdrawalAPI, insertUserWithdrawalAPI, updateUserWithdrawalAPI, withdrawalAPI } from "@/server/api/userwithdrawal.js"

// 数据初始化
const rechargeAddress = ref('');  // 钱包地址或eCNY地址
const rechargeAmount = ref(null);  // 动态绑定提现金额
const OneETHAmount = ref('');
const feePercentage = ref(0);  // 手续费百分比
const finalAmount = ref(0);  // 最终金额
const selectedCurrency = ref('eCNY');  // 提现货币类型，默认为 eCNY
const uId = useUseStore().userId;
const StoreUserInformation = ref(null);
// 提现记录数组
const withdrawalRecords = ref([]);

const closeQRCode = () => {
  const container = document.getElementById('qr-code-container');
  if (container) {
    // 清空容器的内容
    container.innerHTML = '';
  }
};

// 获取手续费百分比
const fetchFeePercentage = async () => {
  try {
    const response = await withdrawalAPI(); // 获取手续费的API
    if (response.data.code == 200) {
      feePercentage.value = response.data.data[0].serviceCharge;
      calculateFinalAmount();  // 在手续费更新后调用计算最终金额
    } else {
      ToastFun("show", { msg: "获取手续费失败" });
    }
  } catch (error) {
    console.error("获取手续费失败:", error);
  }
};

// 计算最终提现金额
const calculateFinalAmount = async () => {
  let amount = parseFloat(rechargeAmount.value);
  // 如果输入金额有效，计算最终金额
  if (!isNaN(amount) && amount > 0) {
    finalAmount.value = (amount * (1 - feePercentage.value / 100)).toFixed(6);  // 按照手续费计算最终金额
  } else {
    finalAmount.value = 0;
  }
};

// 判断金额是否大于等于100且不为负数
const validateAmount = () => {
  let amount = parseFloat(rechargeAmount.value);

  // 如果输入为空或者不是数字，直接返回
  if (isNaN(amount)) {
    ToastFun("show", { msg: t("exchangeTopUp.inputDigit") });
    return;
  }
  // 保留六位小数
  rechargeAmount.value = amount.toFixed(6);

  // 计算最终金额
  calculateFinalAmount();  // 调用计算最终金额的方法

  if (amount < 100) {
    // 如果金额小于100，提示用户并修改为100
    ToastFun("show", { msg: t("exchangeTopUp.amountMin") });
    rechargeAmount.value = "100.000000";
  } else if (amount < 0) {
    // 如果金额为负数，提示用户并修改为0
    ToastFun("show", { msg: t("exchangeTopUp.amountNegative") });
    rechargeAmount.value = "0.000000";
  }
};

// 验证钱包地址是否合法
const validateAddress = () => {
  const address = rechargeAddress.value;

  // 正则表达式：只允许字母和数字
  const addressPattern = /^[A-Za-z0-9]+$/;

  // 如果地址不符合规则，显示提示并清空输入框
  if (!addressPattern.test(address)) {
    ToastFun("show", { msg: t("exchangeTopUp.invalidAddress") });  // 提示信息
    rechargeAddress.value = '';  // 清空输入框
  }
};

const openRecharge = async () => {
  const userId = StoreUserInformation.value.data.data.id;  // 从用户信息中获取用户名
  const uId = StoreUserInformation.value.data.data.uid;
  const walletAddress = rechargeAddress.value;  // 获取钱包地址
  const cashWithdrawalAmount = rechargeAmount.value;  // 获取提现金额
  const FinalAmount = finalAmount.value;  // 最终提现金额

  // 如果地址或金额无效，显示提示
  if (!walletAddress || !cashWithdrawalAmount || parseFloat(cashWithdrawalAmount) <= 0) {
    ToastFun("show", { msg: t("exchangeTopUp.invalidAmountOrAddress") });
    return;
  }

  try {
    // 调用 API 请求，假设 API 地址为 `/api/withdraw`
    const response = await insertUserWithdrawalAPI(userId, uId, walletAddress, cashWithdrawalAmount, FinalAmount);
    if (response.data.code ==200) {
      ToastFun("show", { msg: t("pay.success2") });
    } else {
      ToastFun("show", { msg: t("pay.fail2") });
    }
  } catch (error) {
    ToastFun("show", { msg: t("pay.fail2") });
    console.error("Request failed:", error);
  }
};

// 获取提现记录的API请求
const fetchWithdrawalRecords = async (userId) => {
  try {
    const response = await selectUserWithdrawalAPI(userId);  // 发送请求
    if (response.data.code == 200 ) {
      withdrawalRecords.value = response.data.data;  // 获取提现记录数据
    }
  } catch (error) {
    console.error("Failed to fetch withdrawal records:", error);
  }
};

// 取消操作
const cancelWithdrawal = async (id) => {
  const userId = StoreUserInformation.value.data.data.id;
  try {
    const response = await updateUserWithdrawalAPI(id);  
    if (response.data.code == 200) {
      ToastFun("show", { msg: t("exchangeTopUp.cancelSuccess") });
      // 重新获取提现记录
      fetchWithdrawalRecords(userId);
    } else {
      ToastFun("show", { msg: t("exchangeTopUp.cancelFailed") });
    }
  } catch (error) {
    console.error("Failed to cancel withdrawal:", error);
    ToastFun("show", { msg: t("exchangeTopUp.cancelFailed") });
  }
};

const stateFormatter = (row, column, cellValue) => {
  switch (cellValue) {
    case 0:
      return '申请中';
    case 1:
      return '已完成';
    case 2:
      return '取消提现';
    case 3:
      return '拒绝';
    default:
      return '未知状态';
  }
};

// 计算属性：判断是否显示 "原因" 列
const hasRemarkColumn = computed(() => {
  return withdrawalRecords.value.some(record => record.remark && record.remark.trim() !== '');
});

onMounted(async () => {
  OneETHAmount.value = await computedBuyeCNYApi(1);
  StoreUserInformation.value = await getUserInfoAPI(uId);
  const userId = StoreUserInformation.value.data.data.id;
  fetchWithdrawalRecords(userId);
  fetchFeePercentage();
})
</script>

<template>
  <div class="page-content">
    <!-- 顶部按钮 -->
    <TopButton :title="$t('exchangeTopUp.topUp2')" class="top-button" />

    <!-- 提现卡片 -->
    <div class="recharge-card">
      <!-- 提现类型选择 -->
      <div class="currency-selector">
        <p class="label">{{ t('exchangeTopUp.selectRechargeMethod') }}：</p>
        <el-radio-group v-model="selectedCurrency" @change="closeQRCode()" class="radio-group">
          <el-radio value="eCNY" class="radio-option">
            <img src="https://cryptologos.cc/logos/tether-usdt-logo.png" alt="eCNY" class="currency-icon" />
            eCNY
          </el-radio>
        </el-radio-group>
      </div>
      <p class="currency-type" v-if="selectedCurrency === 'eCNY'">{{
        $t('exchangeTopUp.use_eCNY_to_top_up_points_ratio2')
        }} 1:1</p>

      <!-- 提现地址 -->
      <div class="address-container">
        <p class="label">{{ t('exchangeTopUp.rechargeAddress2') }}</p>
        <el-input v-model="rechargeAddress" class="address-input" :placeholder="t('exchangeTopUp.rechargeAddress2')"
          @blur="validateAddress" />
      </div>

      <!-- 输入提现金额 -->
      <div class="amount-container">
        <p class="label">{{ t('exchangeTopUp.enterRechargeAmount2') }}</p>
        <el-input v-model="rechargeAmount" type="number" class="input-amount"
          :placeholder="t('exchangeTopUp.enterAmount2')" @blur="validateAmount" />
      </div>

      <!-- 显示最终金额 -->
      <div class="amount-container">
        <p class="label">{{ t('exchangeTopUp.finalAmount') }}:{{ finalAmount }}</p>
      </div>

      <!-- 提现按钮 -->
      <el-button @click="openRecharge" type="primary" size="large" class="recharge-button">{{ t('exchangeTopUp.confirm')
        }}</el-button>

      <!-- 提现说明 -->
      <div class="recharge-notice">
        <p>{{ t('exchangeTopUp.rechargeNotice2') }}</p>
        <ul>
          <li>{{ t('exchangeTopUp.minRechargeAmount2') }}</li>
          <li>{{ t('exchangeTopUp.noNonECNYAssets2') }}</li>
          <li>{{ t('exchangeTopUp.networkConfirmationRequired2') }}</li>
          <li>{{ t('exchangeTopUp.securityReminder') }}</li>
        </ul>
      </div>

      <!-- 提现记录表格 -->
      <div class="withdrawal-table">
        <el-table :data="withdrawalRecords" style="width: 100%">
          <el-table-column v-if="false" label="id" prop="id"></el-table-column>
          <el-table-column :label="t('me.PersonalPosting.item.userName')" prop="uid"></el-table-column>
          <el-table-column :label="t('exchangeTopUp.rechargeAddress2')" prop="walletAddress"></el-table-column>
          <el-table-column :label="t('exchangeTopUp.cashWithdrawalAmoun')"
            prop="cashWithdrawalAmount"></el-table-column>
          <el-table-column :label="t('exchangeTopUp.actualAmount')" prop="finalAmount"></el-table-column>
          <el-table-column :label="t('me.PersonalPosting.item.applicationDate')"
            prop="timeOfApplication"></el-table-column>
          <el-table-column :label="t('me.PersonalPosting.item.status')" prop="state"
            :formatter="stateFormatter"></el-table-column>
          <el-table-column v-if="hasRemarkColumn" :label="t('me.PersonalPosting.item.remark')"
            prop="remark"></el-table-column>
          <el-table-column :label="t('me.PersonalPosting.item.operation')">
            <template #default="{ row }">
              <!-- 禁用按钮的逻辑，只有状态为 0 时启用取消操作 -->
              <el-button type="text" @click="cancelWithdrawal(row.id)" size="small" :disabled="row.state !== 0">
                {{ t('exchange.cancel') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>
  </div>
</template>

<style scoped>
/* 适应手机屏幕 */
.page-content {
  padding: 20px;
  background-color: #f8f8f8;
  min-height: 100vh;
  color: #333;
  display: flex;
  flex-direction: column;
  align-items: center;
}

/* 顶部按钮样式 */
.top-button {
  background-color: #333;
  /* 黑色背景 */
  color: white;
  /* 白色文字 */
  padding: 10px 20px;
  /* 给按钮一些内边距 */
  border-radius: 8px;
  /* 按钮圆角 */
  margin-bottom: 20px;
  width: 100%;
}

/* 提现卡片样式 */
.recharge-card {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 100%;
  margin-top: 30px;
  text-align: center;
}

.recharge-card:hover {
  transform: scale(1.02);
}

/* 提现类型选择 */
.currency-selector {
  margin-top: 50px;
  margin-bottom: 30px;
}

.radio-group {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  gap: 50px;
}

.radio-option {
  display: flex;
  align-items: center;
  font-size: 16px;
}

.currency-icon {
  width: 40px;
  height: 40px;
  margin-left: 10px;
  margin-right: 10px;
}

.el-radio-button.is-checked .currency-icon {
  border: 2px solid #007BFF;
  padding: 2px;
  border-radius: 50%;
}

/* 提现按钮样式 */
.recharge-button {
  width: 100%;
  font-size: 16px;
  padding: 12px;
  margin-top: 20px;
  border-radius: 8px;
  background: linear-gradient(135deg, #000000, #000000);
  color: #fff;
}

.recharge-button:hover {
  background-color: #3382c8;
}

/* 输入提现金额样式 */
.amount-container {
  margin-top: 20px;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.amount-container .label {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.input-amount {
  width: 100%;
  font-size: 16px;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ccc;
  border-radius: 5px;
}

/* 提现地址显示容器 */
.address-container {
  margin-top: 20px;
}

.address-container .label {
  font-size: 16px;
  margin-bottom: 10px;
  color: #333;
}

.address-content {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  margin-top: 10px;
}

.address-input {
  font-size: 16px;
  padding: 12px;
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
  flex: 1;
}

.copy-btn {
  width: 40px;
  height: 40px;
  /* display: inline-flex; */
  align-items: center;
  justify-content: center;
  padding: 5px 10px;
  background-color: #e2dada;
  color: rgb(0, 0, 0);
}

.copy-icon {
  font-size: 20px;
}

.qr-code-container {
  margin-top: 20px;
  text-align: center;
}

.currency-type {
  font-size: 14px;
  color: #333;
}

/* 提现说明 */
.recharge-notice {
  margin-top: 30px;
  font-size: 14px;
  color: #666;
  background-color: #f9f9f9;
  /* 背景色 */
  padding: 20px;
  border-radius: 8px;
  /* 圆角 */
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  /* 阴影 */
  border-left: 5px solid transparent;
  /* 为渐变效果做准备 */
  border-image: linear-gradient(to bottom, #c6f1ec, #10c2aa);
  /* 左侧渐变边框 */
  border-image-slice: 1;
  /* 使渐变应用到整个边框 */
}

.recharge-notice p {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  text-transform: uppercase;
  /* 强调标题 */
  letter-spacing: 1px;
  /* 字母间距 */
}

.recharge-notice ul {
  padding-left: 20px;
  text-align: left;
  list-style: none;
  /* 去掉默认项目符号 */
}

.recharge-notice li {
  margin-bottom: 10px;
  line-height: 1.5;
  color: #333;
  position: relative;
  /* 为伪元素提供位置 */
  padding-left: 25px;
  /* 给每个项添加左侧内边距 */
}

.recharge-notice li:before {
  content: '•';
  /* 使用圆点符号 */
  position: absolute;
  left: 0;
  top: 0;
  color: #000000;
  /* 圆点颜色 */
  font-size: 18px;
  /* 圆点大小 */
}

/* 表格样式 */
.withdrawal-table {
  margin-top: 30px;
}

.el-table {
  width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

</style>
